import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { APP_INTERCEPTOR, APP_FILTER } from '@nestjs/core';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';

import { UserModule } from './modules/user/user.module';
import { LoggerModule } from './common/modules/Logger/logger.module';
import { TransformInterceptor } from './common/interceptor/transform.interceptor';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { AnyExceptionFilter } from './common/filters/any-exception.filter';

import { LoggerMiddleware } from './common/middleware/logger.middleware';

import { getDirAllFileNameArr } from './utils/get-dir-all-file-name-arr';
import swaggerOption from './common/config/env/swagger.config';
import databaseOption from './common/config/env/database.config';
import hostOptions from './common/config/env/host.config';
@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: [...getDirAllFileNameArr()],
      load: [hostOptions, swaggerOption, databaseOption],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('DB_HOST'),
        port: configService.get('DB_PORT'),
        username: configService.get('DB_USER'),
        password: configService.get('DB_PWA'),
        database: configService.get('DB_DATABASE'),
        entities: ['dist/**/*.entity.js'],
        synchronize: true,
      }),
      inject: [ConfigService],
    }),

    UserModule,
    LoggerModule,
  ],
  // controllers: [AppController],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: TransformInterceptor,
    },
    {
      provide: APP_FILTER,
      useClass: AnyExceptionFilter,
    },
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
  constructor(private connection: Connection) {}
}
